package com.forezp.servicezuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyFilter extends ZuulFilter{

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public String filterType() {
        return "pre";   //过滤器类型,pre:路由之前,routing:路由之时,post:路由之后,error:发生错误调用
    }

    @Override
    public int filterOrder() {
        return 0;   //过滤顺序
    }

    @Override
    public boolean shouldFilter() {
        return true;    //过滤规则,是否过滤,此处为true表示永远过滤
    }

    @Override
    public Object run() throws ZuulException {
        //过滤器的具体逻辑
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if (accessToken == null){
            log.warn("token is empty!");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty!");
            }catch (Exception e){
                log.error(e.getMessage());
            }
            return null;
        }
        log.info("ok");
        return null;
    }
}
